package com.roan.alipay.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.roan.alipay.prop.AlipayProp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author Roan
 * @date 2025/4/26 23:10
 */
@Configuration
public class AlipayConfig {

    @Autowired
    private AlipayProp alipayProp;

    @Bean
    public AlipayClient apiClient() throws AlipayApiException {
        // 设置alipayConfig参数（全局设置一次）
        com.alipay.api.AlipayConfig config = new com.alipay.api.AlipayConfig();
        config.setServerUrl(alipayProp.getAlipayGatewayUrl());
        config.setAppId(alipayProp.getAppId());
        config.setPrivateKey(alipayProp.getAppSecretKey());
        // 密钥模式
        config.setAlipayPublicKey(alipayProp.getAlipayPublicKey());
        // 证书模式
        // config.setAppCertPath("../appCertPublicKey.crt");
        // config.setAlipayPublicCertPath("../alipayCertPublicKey_RSA2.crt");
        // config.setRootCertPath("../alipayRootCert.crt");
        config.setEncryptKey(alipayProp.getAesKey());
        return new DefaultAlipayClient(config);
    }

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }
}
